package vn.com.pavibook.admin.controller;

import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import vn.com.pavibook.admin.service.ManagePublisherService;
import vn.com.pavibook.admin.service.PersonalInfoService;
import vn.com.pavibook.domain.model.Account;
import vn.com.pavibook.model.vo.ErrorJson;
import vn.com.pavibook.model.vo.PublisherVO;
import vn.com.pavibook.utils.GenerateMD5;

@Controller
public class LoginAdminController {
	private static final Logger logger = LoggerFactory.getLogger(LoginAdminController.class);
	private static final String PHONE_PATTERN = "[0-9]+";
	private static final String EMAIL_PATTERN = 
			"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
			+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
	@Autowired
	private PersonalInfoService personalInfoService;
	@Autowired
	private ManagePublisherService managePublisherService;
	
	@RequestMapping(value="/admin", method=RequestMethod.GET)
	public String checkLogin(Model model){
		return "redirect:admin/login";
	}
	
	@RequestMapping(value="/admin/login", method=RequestMethod.GET)
	public String openLogin(Model model){
		return "admin/login";
	}
	@RequestMapping(value="/admin/loginFailed", method=RequestMethod.GET)
	public String loginFail(Model model){
		return "admin/login";
	}
	
	@RequestMapping(value="/admin/personal-info", method=RequestMethod.GET)
	public String openPersonalInfo(Model model) {
		SecurityContext context = SecurityContextHolder.getContext();
		String username = context.getAuthentication().getName();
		PublisherVO publisherVO = personalInfoService.getPersonalInfo(username);
		model.addAttribute("publisher", publisherVO);
		model.addAttribute("account", personalInfoService.getAccountById(publisherVO.getAccountId()));
		return "admin/personal-info";
	}
	
	@RequestMapping(value="/admin/updateAccountInfo", method=RequestMethod.POST)
	public @ResponseBody ErrorJson updateAccountInfo(
			@RequestParam("id") int id,
			@RequestParam("oldpassword") String oldPass,
			@RequestParam("password") String password,
			@RequestParam("repeatPassword") String rePassword,
			Model model) {
		ErrorJson errorJson = new ErrorJson();
		errorJson.setValidate(false);
		//check username is existed
		if(StringUtils.isEmpty(oldPass)){
			errorJson.setErrorName("Cần nhập thông tin!");
			errorJson.setValidate(true);
		} else if (!managePublisherService.checkOldPass(oldPass, id)) {
			errorJson.setErrorPass("Mật khẩu cũ khồng đúng!");
			errorJson.setValidate(true);
			return errorJson;
		} 
		
		if(StringUtils.isEmpty(password)){
			errorJson.setErrorPass("Cần nhập thông tin mật khẩu mới!");
			errorJson.setValidate(true);
		} 
		
		if(!password.equals(rePassword)) {
			errorJson.setErrorPass("Mật khẩu nhập lại chưa đúng!");
			errorJson.setValidate(true);
		}
		if(errorJson.isValidate()){
			return errorJson;
		}
		try {
			Account account = personalInfoService.getAccountById(id);
			account.setPassword(GenerateMD5.MD5(password));
			personalInfoService.updateAccount(account);
		} catch (Exception e) {
			logger.info("UPDATE ACCOUNT PUBLISHER" + e.getMessage());
			errorJson.setErrorSystem("Error system!");
		}
		
		return errorJson;

	}
	@RequestMapping(value="/admin/updatePersonInfo", method=RequestMethod.POST)
	public @ResponseBody ErrorJson updatePersonalInfo(
			@ModelAttribute("publisher") PublisherVO publisher, Model model) {

		ErrorJson errorJson = new ErrorJson();
		errorJson.setValidate(false);
		Pattern phonePattern = Pattern.compile(PHONE_PATTERN);
		Pattern emailPattern = Pattern.compile(EMAIL_PATTERN);
		if(StringUtils.isEmpty(publisher.getName())){
			errorJson.setErrorName("Cần nhập thông tin!");
			errorJson.setValidate(true);
		}
		if(StringUtils.isEmpty(publisher.getAddress())){
			errorJson.setErrorAddress("Cần nhập thông tin!");
			errorJson.setValidate(true);
		}
		if(StringUtils.isEmpty(publisher.getEmailBussiness())){
			errorJson.setErrorMail("Cần nhập thông tin!");
			errorJson.setValidate(true);
		} else if(!emailPattern.matcher(publisher.getEmailBussiness()).matches()){
			errorJson.setErrorMail("Email không hợp lệ (VD: abc@example.com)!");
			errorJson.setValidate(true);
		}
		if(StringUtils.isEmpty(publisher.getPhone())){
			errorJson.setErrorPhone("Cần nhập thông tin!");
			errorJson.setValidate(true);
		} else if(!phonePattern.matcher(publisher.getPhone()).matches()){
			errorJson.setErrorPhone("Số điện thoại không hợp lệ!");
			errorJson.setValidate(true);
		}
		if(errorJson.isValidate()){
			return errorJson;
		}
		
		try {
			managePublisherService.updatePublisherInfo(publisher);
		} catch (Exception e) {
			logger.info("UpdatePersionalInfo" + e.getMessage());
			errorJson.setValidate(true);
			errorJson.setErrorSystem(e.getMessage());
		}
		
		return errorJson;

	}
	
	@RequestMapping(value="/page-not-found", method=RequestMethod.GET)
	public String pageNotFound(Model model){
		return "errorPages/PageNotFound";
	}
	
}
